const HARMON_EDITOR_URL = 'http://hanma-paas-dev.hancode.com/mdesigner/#/editor'
class FreeEditor {
  constructor() {
    this.editorUrl = null // 编辑器地址
    this.editorInstance = null // 编辑器窗口实例
    this.editorOptions = {} // 其他配置
    this.editorLang = null // 当前tab

    this.init()
  }

  /**
   * 编辑器页面统一使用移动端地址
   * app开发环境需要启动browser环境
   */
  init() {
    const {
      protocol,
      hostname,
      origin
    } = location
    let editorUrl = ''
    if (process.env.NODE_ENV === 'development') {
      if (process.env.VUE_APP_PROJECT === 'Mobile-fed') {
        editorUrl = protocol + "//" + hostname + ":9991/mdesigner/#/editor";
      } else {
        editorUrl = HARMON_EDITOR_URL;
      }
    } else {
      editorUrl = origin + "/mdesigner/#/editor";
    }
    this.editorUrl = editorUrl
  }

  open(options = {}) {
    this.editorOptions = options
    this.editorInstance = window.open(
      this.editorUrl,
      'freeEditorWin'+this.editorOptions.formData.key,
      'width=1000,height=600,left=100,top=60'
    )
    
    this.messageHandler = this.messageHandler.bind(this)

    window.addEventListener('message', this.messageHandler, false)
    window.addEventListener('beforeunload', () => {
      this.close()
    })
  }
  errorPostMessage(){
    this.editorInstance.postMessage({
      _type_: "UNDIFINEND",
    }, "*");
  }
  close() {
    window.removeEventListener('message', this.messageHandler, false)
    if (!this.editorInstance) return
    this.editorInstance.close()
    this.editorInstance = null
  }
  passiveClose(options) {
    if (!this.editorInstance) return
    this.editorOptions = options
    this.editorInstance.postMessage({
      _type_: "FREE_EDITOR_FORCESAVE",
    }, "*");
  }
  messageHandler(event) {
    if (typeof event.data !== 'object') return
    const {
      _type_,
      js,
      css,
      key
    } = event.data
    if (_type_ === 'FREE_EDITOR_READY') {
      this.editorInstance && this.editorInstance.postMessage({
          _type_: 'FREE_EDITOR_INIT',
          ...this.editorOptions.formData,
          lang: this.editorOptions.lang,
          title: this.editorOptions.title
        },
        '*'
      )
    } else if (_type_ === 'FREE_EDITOR_SAVE') {
      const {
        save
      } = this.editorOptions
      if (!save) return
      save({
        js,
        css,
        key
      })
      // this.close()
    }
  }
}

export default FreeEditor